<template>
  <div class="content-block">
    <h4>{{ t('settings.signCodeTitle') }}</h4>
    <input
        type="text"
        :placeholder="t('placeholder.enterSignCode')"
        maxlength="8"
        ref="codeInput"
        class="compact-input"
        @blur="validateCodeLength"
    >
    <p v-if="error" class="error-message">{{ error }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const codeInput = ref(null)
const error = ref(null)

const validateCodeLength = () => {
  if (codeInput.value) {
    const value = codeInput.value.value
    error.value = null
    if (value.length < 4) {
      error.value = t('error.codeMinLength', { min: 4 })
    } else if (value.length > 8) {
      error.value = t('error.codeMaxLength', { max: 8 })
      codeInput.value.value = value.substring(0, 8)
    }
  }
}

// 提供获取和重置签到码的方法
const getCode = () => {
  return codeInput.value ? codeInput.value.value : ''
}

const resetCode = () => {
  if (codeInput.value) {
    codeInput.value.value = ''
    error.value = null
  }
}
import { defineExpose } from 'vue'
// 定义暴露的方法
defineExpose({
  getCode,
  resetCode
})
</script>

<style scoped>
.content-block {
  padding: 1.5vh 0;
}

.content-block h4 {
  margin: 0.5vh 0;
  font-size: 14px;
  font-weight: 500;
}

.compact-input {
  flex: 1;
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 3px;
  font-size: 13px;
  height: 28px;
}

.error-message {
  color: red;
  font-size: 12px;
  margin-top: 5px;
}
</style>